{% extends "member/layout.html" %}

{% block title %}编辑任务 - {{ task.name }}{% endblock %}

{% block content %}
    <div class="d-flex flex-column h-100">
        <!-- 页面标题区域 - 优化视觉层次 -->
        <div class="mb-4">
            <div class="d-flex align-items-center justify-content-between">
                <div>
                    <h2 class="h3 fw-bold mb-1">
                        <i class="fas fa-edit me-2 text-primary"></i>编辑任务
                    </h2>
                    <p class="text-muted mb-0">修改任务信息，更新负责人或截止日期</p>
                </div>
                <a href="{{ url_for('member.task.task_detail', task_id=task.id) }}"
                   class="btn btn-outline-secondary rounded-pill">
                    <i class="fas fa-arrow-left me-2"></i>返回详情
                </a>
            </div>
            <hr class="mt-3 mb-0">
        </div>

        <!-- 任务编辑表单 - 优化布局和视觉设计 -->
        <div class="dashboard-card flex-grow-1">
            <div class="card-body p-4 h-100">
                <div class="row h-100 g-0">
                    <!-- 左侧：表单区域 - 添加卡片式设计 -->
                    <div class="col-lg-7 pe-lg-4 border-end border-light">
                        <div class="bg-white rounded-lg p-4 shadow-sm">
                            <form method="post" id="editForm" class="h-100 d-flex flex-column">
                                {{ form.csrf_token }}

                                <!-- 任务名称 - 增强输入框样式 -->
                                <div class="mb-4">
                                    <label for="name" class="form-label fw-semibold mb-2">
                                        <i class="fas fa-tag me-2 text-primary"></i>任务名称
                                        <span class="text-danger">*</span>
                                    </label>
                                    <input type="text" class="form-control form-control-lg bg-light" id="name" name="name"
                                           value="{{ form.name.data }}" required>
                                </div>

                                <!-- 任务描述 - 优化文本区域样式 -->
                                <div class="mb-4">
                                    <label for="description" class="form-label fw-semibold mb-2">
                                        <i class="fas fa-file-alt me-2 text-primary"></i>任务描述
                                    </label>
                                    <textarea class="form-control form-control-lg bg-light" id="description" name="description"
                                              rows="4">{{ form.description.data }}</textarea>
                                    <div class="d-flex justify-content-between align-items-center mt-2">
                                        <div class="form-text">
                                            <i class="fas fa-lightbulb me-1"></i>清晰的描述有助于负责人理解任务要求
                                        </div>
                                        <div class="text-muted small">
                                            <span id="charCount">{{ form.description.data|length if form.description.data else 0 }}</span>/500
                                        </div>
                                    </div>
                                </div>

                                <!-- 现有附件 - 优化列表样式 -->
                                {% if attachments %}
                                    <div class="mb-4">
                                        <label class="form-label fw-semibold mb-2">
                                            <i class="fas fa-paperclip me-2 text-primary"></i>现有附件
                                        </label>
                                        <div class="list-group">
                                            {% for attachment in attachments %}
                                                <div class="list-group-item d-flex align-items-center justify-content-between hover-shadow {% if loop.first %}bg-light{% endif %}">
                                                    <div class="d-flex align-items-center flex-grow-1">
                                                        <div class="me-3">
                                                            <i class="fas {{
                                                                    'fa-file-image text-info' if attachment.filename.split('.')[-1]|lower in ['jpg','jpeg','png','gif']
                                                                    else 'fa-file-pdf text-danger' if attachment.filename.split('.')[-1]|lower == 'pdf'
                                                                    else 'fa-file-word text-primary' if attachment.filename.split('.')[-1]|lower in ['doc','docx']
                                                                    else 'fa-file-excel text-success' if attachment.filename.split('.')[-1]|lower in ['xls','xlsx']
                                                                    else 'fa-file-archive text-warning' if attachment.filename.split('.')[-1]|lower in ['zip','rar']
                                                                    else 'fa-file text-secondary'
                                                                    }} fa-lg"></i>
                                                        </div>
                                                        <div class="flex-grow-1">
                                                            <div class="fw-medium text-truncate" style="max-width: 300px;">{{ attachment.filename }}</div>
                                                            <div>
                                                                <small class="text-muted">{{ attachment.created_at.strftime('%Y-%m-%d %H:%M') }}</small>
                                                            </div>
                                                        </div>
                                                    </div>
                                        <div class="btn-group btn-group-sm">
                                            <a href="{{ url_for('member.task.download_attachment', attachment_id=attachment.id) }}"
                                               class="btn btn-outline-primary" title="下载">
                                                <i class="fas fa-download"></i>
                                            </a>
                                            {% if attachment.uploader_id == current_member.id or task.stage.project.owner_id == current_member.id %}
                                            <button class="btn btn-outline-danger delete-attachment"
                                                data-attachment-id="{{ attachment.id }}"
                                                data-csrf-token="{{ form.csrf_token._value() }}"
                                                title="删除">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            {% endif %}
                                        </div>
                                                </div>
                                            {% endfor %}
                                        </div>
                                    </div>
                                {% endif %}

                                <!-- 附件上传 - 优化上传区域样式 -->
                                <div class="mb-4">
                                    <label class="form-label fw-semibold mb-2">
                                        <i class="fas fa-paperclip me-2 text-primary"></i>添加附件
                                    </label>
                                    <div class="file-upload-area border rounded-3 p-3 bg-light">
                                        <div class="d-flex flex-column align-items-center justify-content-center py-4">
                                            <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                                            <h6 class="mb-2">拖放文件到此处或点击上传</h6>
                                            <p class="text-muted small mb-3">支持单个或多个文件上传</p>
                                            <button type="button" class="btn btn-sm btn-primary rounded-pill" id="selectFilesBtn">
                                                <i class="fas fa-folder-open me-1"></i>选择文件
                                            </button>
                                        </div>
                                        <input type="file" class="d-none" id="fileInput" name="files" multiple>
                                        <div class="file-preview mt-3" id="filePreview"></div>
                                    </div>
                                </div>

                                <!-- 负责人和截止日期 - 优化布局 -->
                                <div class="row mb-4">
                                    <div class="col-md-6">
                                        <label for="assignee_id" class="form-label fw-semibold mb-2">
                                            <i class="fas fa-user-check me-2 text-primary"></i>负责人
                                        </label>
                                        <select class="form-select form-select-lg bg-light" id="assignee_id" name="assignee_id" required>
                                            {% for member_id, member_name in form.assignee_id.choices %}
                                                <option value="{{ member_id }}"
                                                        {% if member_id == form.assignee_id.data %}selected{% endif %}>
                                                    {{ member_name }}
                                                </option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="due_date" class="form-label fw-semibold mb-2">
                                            <i class="fas fa-calendar-day me-2 text-primary"></i>截止日期
                                        </label>
                                        <input type="date" class="form-control form-control-lg bg-light" id="due_date" name="due_date"
                                               value="{{ form.due_date.data.strftime('%Y-%m-%d') if form.due_date.data else '' }}">
                                    </div>
                                </div>

                                <!-- 任务优先级 - 优化按钮样式 -->
                                <div class="mb-4">
                                    <label class="form-label fw-semibold mb-2">
                                        <i class="fas fa-flag me-2 text-primary"></i>任务优先级
                                    </label>
                                    <div class="priority-selector">
                                        <div class="row g-2">
                                            <div class="col-md-4">
                                                <input type="radio" class="btn-check" name="priority" id="priority-low"
                                                       value="low" {% if form.priority.data == 'low' %}checked{% endif %}>
                                                <label class="btn btn-outline-success w-100 d-flex align-items-center justify-content-center rounded-pill" for="priority-low">
                                                    <i class="fas fa-arrow-down me-2"></i>低优先级
                                                </label>
                                            </div>
                                            <div class="col-md-4">
                                                <input type="radio" class="btn-check" name="priority" id="priority-medium"
                                                       value="medium" {% if form.priority.data == 'medium' %}checked{% endif %}>
                                                <label class="btn btn-outline-warning w-100 d-flex align-items-center justify-content-center rounded-pill" for="priority-medium">
                                                    <i class="fas fa-minus me-2"></i>中优先级
                                                </label>
                                            </div>
                                            <div class="col-md-4">
                                                <input type="radio" class="btn-check" name="priority" id="priority-high"
                                                       value="high" {% if form.priority.data == 'high' %}checked{% endif %}>
                                                <label class="btn btn-outline-danger w-100 d-flex align-items-center justify-content-center rounded-pill" for="priority-high">
                                                    <i class="fas fa-arrow-up me-2"></i>高优先级
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- 操作按钮 - 优化按钮样式 -->
                                <div class="mt-auto pt-4">
                                    <div class="d-flex justify-content-end gap-3">
                                        <a href="{{ url_for('member.task.task_detail', task_id=task.id) }}"
                                           class="btn btn-light px-4 rounded-pill">
                                            <i class="fas fa-times me-2"></i>取消
                                        </a>
                                        <button type="submit" class="btn btn-primary px-4 rounded-pill">

                                            <i class="fas fa-save me-2"></i>保存更改
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- 右侧：预览区域 - 优化卡片样式 -->
                    <div class="col-lg-5 ps-lg-4">
                        <div class="sticky-top" style="top: 100px;">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5 class="fw-bold mb-0">
                                    <i class="fas fa-eye me-2 text-primary"></i>任务预览
                                </h5>
                                <button type="button" class="btn btn-sm btn-outline-primary rounded-pill" id="togglePreview">
                                    <i class="fas fa-sync-alt me-1"></i>刷新预览
                                </button>
                            </div>

                            <div class="preview-container bg-white rounded-lg p-4 shadow-sm">
                                <div class="preview-content">
                                    <!-- 任务标题预览 -->
                                    <div class="d-flex align-items-center mb-3 pb-3 border-bottom">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm bg-primary bg-opacity-10 text-primary rounded-circle d-flex align-items-center justify-content-center me-3">
                                                <i class="fas fa-tasks"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="fw-bold mb-1" id="previewName">{{ form.name.data }}</h6>
                                            <span class="badge {% if form.priority.data == 'low' %}bg-success{% elif form.priority.data == 'medium' %}bg-warning{% else %}bg-danger{% endif %}"
                                                  id="previewPriority">
                                            {% if form.priority.data == 'low' %}低优先级
                                            {% elif form.priority.data == 'medium' %}中优先级
                                            {% else %}高优先级{% endif %}
                                        </span>
                                        </div>
                                    </div>

                                    <!-- 任务详情预览 -->
                                    <div class="mb-3">
                                        <p class="text-muted small mb-2">任务描述</p>
                                        <p class="mb-0" id="previewDescription">
                                            {{ form.description.data if form.description.data else '暂无任务描述' }}
                                        </p>
                                    </div>

                                    <!-- 任务元信息 -->
                                    <div class="row g-2">
                                        <div class="col-6">
                                            <div class="bg-light rounded p-2 border">
                                                <p class="text-muted small mb-1">负责人</p>
                                                <p class="fw-medium mb-0" id="previewAssignee">
                                                    {% for member_id, member_name in form.assignee_id.choices %}
                                                        {% if member_id == form.assignee_id.data %}{{ member_name }}{% endif %}
                                                    {% endfor %}
                                                </p>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="bg-light rounded p-2 border">
                                                <p class="text-muted small mb-1">截止日期</p>
                                                <p class="fw-medium mb-0" id="previewDueDate">
                                                    {{ form.due_date.data.strftime('%Y-%m-%d') if form.due_date.data else '未设置' }}
                                                </p>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 状态指示器 -->
                                    <div class="mt-3 pt-3 border-top">
                                        <div class="d-flex align-items-center">
                                            <div class="flex-shrink-0">
                                                <div class="avatar-xs bg-secondary bg-opacity-10 text-secondary rounded-circle d-flex align-items-center justify-content-center">
                                                    <i class="fas fa-clock"></i>
                                                </div>
                                            </div>
                                            <div class="flex-grow-1 ms-2">
                                                <p class="small text-muted mb-0">任务状态: <span class="fw-medium">{{ task.status_label }}</span></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 提示信息 -->
                            <div class="mt-3">
                                <div class="alert alert-info border-0 py-2">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-info-circle me-2"></i>
                                        <small>修改表单时，右侧预览将实时更新</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        /* 增强输入框样式 */
        .form-control-lg, .form-select-lg {
            border-radius: 12px;
            border: 1px solid #e2e8f0;
            padding: 0.85rem 1.25rem;
            transition: all 0.3s;
            box-shadow: 0 2px 4px rgba(0,0,0,0.02);
        }

        .form-control-lg:focus, .form-select-lg:focus {
            border-color: #4361ee;
            box-shadow: 0 0 0 0.25rem rgba(67, 97, 238, 0.15);
        }

        /* 优化标签样式 */
        .form-label {
            color: #374151;
            font-size: 0.95rem;
            font-weight: 500;
        }

        /* 预览容器样式 */
        .preview-container {
            border-left: 4px solid #4361ee;
            min-height: 300px;
            transition: all 0.3s ease;
            border-radius: 12px;
        }

        /* 按钮样式 */
        .btn {
            border-radius: 8px;
            font-weight: 500;
            padding: 0.65rem 1.5rem;
            transition: all 0.2s;
        }

        .btn-primary {
            background-color: #4361ee;
            border-color: #4361ee;
        }

        .btn-primary:hover {
            background-color: #3a56d4;
            border-color: #3a56d4;
        }

        /* 优先级按钮样式 */
        .priority-selector .btn {
            padding: 0.85rem 0.5rem;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s;
        }

        .priority-selector .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        /* 头像样式 */
        .avatar-sm {
            width: 45px;
            height: 45px;
            font-size: 1.1rem;
        }

        .avatar-xs {
            width: 32px;
            height: 32px;
            font-size: 0.9rem;
        }

        /* 响应式调整 */
        @media (max-width: 991.98px) {
            .border-end {
                border-right: none !important;
                border-bottom: 1px solid rgba(0,0,0,.1) !important;
                padding-bottom: 2rem;
                margin-bottom: 2rem;
            }

            .ps-lg-4 {
                padding-left: 0 !important;
            }

            .pe-lg-4 {
                padding-right: 0 !important;
            }

            .row.g-0 > .col-lg-7, .row.g-0 > .col-lg-5 {
                padding-left: 0 !important;
                padding-right: 0 !important;
            }
        }

        /* 粘性顶部边距 */
        .sticky-top {
            top: 100px;
            z-index: 10;
        }

        /* 文件上传区域样式 */
        .file-upload-area {
            transition: all 0.3s;
            border: 2px dashed #e2e8f0;
        }

        .file-upload-area:hover {
            border-color: #4361ee;
            background-color: #f8f9fe;
        }

        /* 文件预览项样式 */
        .file-preview-item {
            transition: all 0.2s;
            border-radius: 8px;
        }

        .file-preview-item:hover {
            background-color: #f8f9fe;
            transform: translateX(5px);
        }

        /* 阴影效果 */
        .hover-shadow {
            transition: all 0.3s;
        }

        .hover-shadow:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            transform: translateY(-2px);
        }
    </style>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 元素引用
            const nameInput = document.getElementById('name');
            const descriptionTextarea = document.getElementById('description');
            const assigneeSelect = document.getElementById('assignee_id');
            const dueDateInput = document.getElementById('due_date');
            const previewName = document.getElementById('previewName');
            const previewDescription = document.getElementById('previewDescription');
            const previewAssignee = document.getElementById('previewAssignee');
            const previewDueDate = document.getElementById('previewDueDate');
            const previewPriority = document.getElementById('previewPriority');
            const charCount = document.getElementById('charCount');
            const priorityRadios = document.querySelectorAll('input[name="priority"]');
            const togglePreview = document.getElementById('togglePreview');
            const fileInput = document.getElementById('fileInput');
            const selectFilesBtn = document.getElementById('selectFilesBtn');
            const filePreview = document.getElementById('filePreview');
            const fileUploadArea = document.querySelector('.file-upload-area');
            const form = document.getElementById('editForm');

            // 字符计数
            descriptionTextarea.addEventListener('input', function() {
                const count = this.value.length;
                charCount.textContent = count;
                charCount.classList.toggle('text-danger', count > 500);
                updatePreview();
            });

            // 刷新预览按钮
            togglePreview.addEventListener('click', updatePreview);

            // 实时更新预览
            function updatePreview() {
                // 更新任务名称预览
                previewName.textContent = nameInput.value || '任务名称';

                // 更新任务描述预览
                const desc = descriptionTextarea.value;
                previewDescription.textContent = desc ?
                    (desc.length > 120 ? desc.substring(0, 120) + '...' : desc) : '暂无任务描述';

                // 更新负责人预览
                const selectedAssignee = assigneeSelect.options[assigneeSelect.selectedIndex];
                previewAssignee.textContent = selectedAssignee.text || '未选择';

                // 更新截止日期预览
                previewDueDate.textContent = dueDateInput.value ?
                    new Date(dueDateInput.value).toLocaleDateString('zh-CN') : '未设置';

                // 更新优先级预览
                const selectedPriority = document.querySelector('input[name="priority"]:checked');
                if (selectedPriority) {
                    const badgeClass = selectedPriority.value === 'low' ? 'bg-success' :
                        selectedPriority.value === 'medium' ? 'bg-warning' : 'bg-danger';
                    const badgeText = selectedPriority.value === 'low' ? '低优先级' :
                        selectedPriority.value === 'medium' ? '中优先级' : '高优先级';
                    previewPriority.className = `badge ${badgeClass}`;
                    previewPriority.textContent = badgeText;
                }
            }

            // 事件监听
            nameInput.addEventListener('input', updatePreview);
            assigneeSelect.addEventListener('change', updatePreview);
            dueDateInput.addEventListener('change', updatePreview);
            priorityRadios.forEach(radio => {
                radio.addEventListener('change', updatePreview);
            });

            // 文件上传处理
            selectFilesBtn.addEventListener('click', () => fileInput.click());
            fileInput.addEventListener('change', handleFileSelect);

            // 拖放事件
            fileUploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                fileUploadArea.classList.add('bg-light');
            });

            fileUploadArea.addEventListener('dragleave', () => {
                fileUploadArea.classList.remove('bg-light');
            });

            fileUploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                fileUploadArea.classList.remove('bg-light');
                fileInput.files = e.dataTransfer.files;
                handleFileSelect({ target: fileInput });
            });

            // 处理文件选择
            function handleFileSelect(event) {
                filePreview.innerHTML = '';
                const files = event.target.files;

                if (files.length > 0) {
                    fileUploadArea.querySelector('.d-flex').classList.add('d-none');

                    for (let i = 0; i < files.length; i++) {
                        const file = files[i];
                        const fileItem = document.createElement('div');
                        fileItem.className = 'd-flex align-items-center justify-content-between mb-2 p-3 file-preview-item bg-light rounded';
                        fileItem.innerHTML = `
                    <div class="d-flex align-items-center">
                        <i class="fas ${getFileIcon(file.name)} me-3 text-muted"></i>
                        <div>
                            <div class="small">${file.name}</div>
                            <div class="text-muted extra-small">${formatFileSize(file.size)}</div>
                        </div>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-danger rounded-circle remove-file" data-index="${i}">
                        <i class="fas fa-times"></i>
                    </button>
                `;
                        filePreview.appendChild(fileItem);
                    }
                } else {
                    fileUploadArea.querySelector('.d-flex').classList.remove('d-none');
                }

                // 添加移除文件事件
                document.querySelectorAll('.remove-file').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const index = this.dataset.index;
                        const files = Array.from(fileInput.files);
                        files.splice(index, 1);

                        // 更新文件输入
                        const dataTransfer = new DataTransfer();
                        files.forEach(file => dataTransfer.items.add(file));
                        fileInput.files = dataTransfer.files;

                        // 重新渲染预览
                        handleFileSelect({ target: fileInput });
                    });
                });
            }

            // 获取文件图标
            function getFileIcon(filename) {
                const ext = filename.split('.').pop().toLowerCase();
                const icons = {
                    pdf: 'fa-file-pdf',
                    doc: 'fa-file-word',
                    docx: 'fa-file-word',
                    xls: 'fa-file-excel',
                    xlsx: 'fa-file-excel',
                    ppt: 'fa-file-powerpoint',
                    pptx: 'fa-file-powerpoint',
                    jpg: 'fa-file-image',
                    jpeg: 'fa-file-image',
                    png: 'fa-file-image',
                    gif: 'fa-file-image',
                    zip: 'fa-file-archive',
                    rar: 'fa-file-archive',
                    txt: 'fa-file-alt',
                    csv: 'fa-file-csv'
                };
                return icons[ext] || 'fa-file';
            }

            // 格式化文件大小
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }

            // 简化的表单提交处理
            form.addEventListener('submit', function(e) {
                console.log('表单提交开始');

                // 基本验证
                if (!nameInput.value.trim()) {
                    e.preventDefault();
                    alert('请填写任务名称');
                    nameInput.focus();
                    return false;
                }

                // 显示加载状态
                const submitBtn = form.querySelector('button[type="submit"]');
                const originalText = submitBtn.innerHTML;
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>保存中...';

                // 如果表单包含文件，设置正确的编码类型
                if (fileInput.files.length > 0) {
                    form.enctype = 'multipart/form-data';
                }

                console.log('表单验证通过，正在提交...');
                // 允许表单正常提交
                return true;
            });

            // 初始化预览
            updatePreview();
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log('页面加载完成');

            // 立即检查关键元素
            const form = document.getElementById('editForm');
            const submitBtn = form ? form.querySelector('button[type="submit"]') : null;

            console.log('表单元素:', form);
            console.log('提交按钮:', submitBtn);

            if (!form) {
                console.error('错误: 找不到表单元素');
                alert('表单加载错误，请刷新页面重试');
                return;
            }

            if (!submitBtn) {
                console.error('错误: 找不到提交按钮');
                alert('提交按钮加载错误，请刷新页面重试');
                return;
            }

            // 其他代码保持不变...
        });
    </script>

    <script>
    // 统一删除附件处理
    function handleDeleteAttachment(button) {
        const attachmentId = button.dataset.attachmentId;
        const csrfToken = button.dataset.csrfToken;

        if (!confirm('确定要删除此附件吗？')) return;

        fetch(`/member/task/attachment/${attachmentId}/delete`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify({})
        })
        .then(response => {
            if (!response.ok) throw new Error('网络响应异常');
            return response.json();
        })
        .then(data => {
            if (data.success) {
                // 局部刷新附件列表
                const attachmentItem = button.closest('.list-group-item');
                attachmentItem.remove();

                // 如果没有附件了，显示提示
                if (!document.querySelector('.list-group-item')) {
                    document.querySelector('.list-group').innerHTML =
                        '<p class="text-muted">暂无附件</p>';
                }
            } else {
                alert(data.message || '删除失败');
            }
        })
        .catch(error => {
            console.error('删除附件错误:', error);
            alert('删除失败，请检查网络或刷新页面重试');
        });
    }

    // 为所有删除按钮绑定事件
    document.querySelectorAll('.delete-attachment').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault(); // 阻止默认行为
            e.stopPropagation(); // 阻止事件冒泡
            handleDeleteAttachment(this);
        });
    });
    </script>

{% endblock %}